<template>
<view>
<view class="container">
  <view class="typeSearchContainer1"> 
      <view class="search_input_bg">
        <view class="search_input">
          <view class="search_input_left">
            <image class="input_img" src="https://image1.sansancloud.com/xianhua/2018_9/14/16/25/0_222.jpg?x-oss-process=style/preview_120"></image>
            <!--   data-link="search_page.html"  bindtap='linkUrl'-->
            <input class="input" @confirm="getSearchProductName" placeholder="搜索产品名或编码" :value="searchProductName"></input>
          </view>
          <view class="empty_button" @tap="getSearchProductName"><text>x</text></view>
        </view>
        <view class="search_product_type" @click.stop="selectPopupType">
          <image class="search_product_type_icon" src="https://image1.sansancloud.com/xianhua/2019_8/19/10/34/19_335.jpg?x-oss-process=style/preview_120"></image>
          <text class="search_product_type_text">分类</text>
        </view>
      </view>
  </view>
  <!-- 产品分类弹窗 -->
  <select-product-type-popup-component :productType="productType" id="select-product-type-popup" v-if="productTypePopupState&&productType" @sureSelect="getChilrenPopupType"></select-product-type-popup-component>
  <view class="top_meun_tab">
    <view class="top_meun_tab_item" v-for="(tabItem, index) in tabItem" :key="index" @click.stop="changeProductState" :data-index="tabItem.status" :style="'border-color:' + (tabItem.status==currentIndex?setting.platformSetting.defaultColor:'#fff') + ';color:' + (tabItem.status==currentIndex?setting.platformSetting.defaultColor:'')">
      <text>{{tabItem.text}}</text>
    </view>
  </view>
  <!-- 产品列表 -->
  <view class="product_list" v-if="mendianProductsList.length!=0">
    <view class="product_item" v-for="(mendianProductItem, index) in mendianProductsList" :key="index" :data-info="mendianProductItem" @tap="tolinkUrl">
      <view class="product_item_main_info">
        <view class="product_item_main_img">
          <image class="product_img" :src="mendianProductItem.imagePath"></image>
        </view>
        <view class="priduct_info">
          <text class="product_name">{{mendianProductItem.name}}</text>
          <text class="product_price" :style="'color:' + setting.platformSetting.defaultColor">最高供应价：￥{{mendianProductItem.supplyPrice}}</text>
          <view class="product_info_bottom">
            <view class="product_stock" v-if="mendianProductItem.mendianStorages.length!=0&&mendianProductItem.measureItem!=1">商家供货价：<text class="product_stock_num">{{mendianProductItem.mendianStorages[0].supplyPrice}}</text></view>
            <!-- <view class='product_stock'>库存：<text class='product_stock_num'>{{mendianProductItem.stock}}</text></view> -->
            <!-- <view class='product_sales'>销量：<text class='product_sales_num'></text></view> -->
          </view>
        </view>
        <view class="handle_btn">
          <text class="handle_item" v-if="mendianProductItem.mendianStorages&&mendianProductItem.mendianStorages.length!=0" :data-info="mendianProductItem" @click.stop="soldOutFun">下架</text>
          <text class="handle_item" v-else :data-info="mendianProductItem" @click.stop="putAwayFun">上架</text>
          <text class="handle_item" :data-info="mendianProductItem" v-if="mendianProductItem.measureItem!=1" :data-type="(mendianProductItem.mendianStorages&&mendianProductItem.mendianStorages.length!=0?'up':'down')" @click.stop="editProductData">编辑</text>
        </view>
        <!-- 操作按钮 -->
        <!-- <view class='handle_btn' data-id="{{mendianProductItem.id}}" catchtap='showHandleListFun'>
          <image class='handle_btn_icon' src='https://image1.sansancloud.com/xianhua/2019_8/1/14/47/2_829.jpg?x-oss-process=style/preview_120'></image>
          <view class='handle_list' animation="{{animationData}}" wx:if="{{showHandleListState['showHandleListState_'+mendianProductItem.id]}}">
            <view class='handle_item_bg'>
              <view class='handle_item' wx:if="{{mendianProductItem.mendianStorages&&mendianProductItem.mendianStorages.length!=0}}" data-info="{{mendianProductItem}}" catchtap='soldOutFun'>
                <image class='handle_item_icon' src='https://image1.sansancloud.com/xianhua/2019_8/2/16/28/11_596.jpg?x-oss-process=style/preview_120'></image>
                <text>下架</text>
              </view>
              <view class='handle_item' wx:else data-info="{{mendianProductItem}}" catchtap='putAwayFun'>
                <image class='handle_item_icon' src='https://image1.sansancloud.com/xianhua/2019_8/5/14/27/40_365.jpg?x-oss-process=style/preview_120'></image>
                <text>上架</text>
              </view>
              <view class='handle_item' data-info="{{mendianProductItem}}" data-type="up" catchtap='editProductData'>
                <image class='handle_item_icon' src='https://image1.sansancloud.com/xianhua/2019_8/2/16/28/37_743.jpg?x-oss-process=style/preview_120'></image>
                <text>编辑</text>
              </view>
            </view>
            <view class='triangle-right'></view>
          </view>
        </view> -->
      </view>
      <!-- 操作显示多规格产品 -->
      <view class="more_measure_btn" :data-id="mendianProductItem.id" v-if="mendianProductItem.measureItem==1&&currentIndex!=0" @click.stop="showMeasureListFun">
        <image class="more_measure_btn_icon" v-if="!showMeasureListState['showMeasureListState_'+mendianProductItem.id]" src="https://image1.sansancloud.com/xianhua/2019_8/2/15/22/51_366.jpg?x-oss-process=style/preview_120"></image>
        <image class="more_measure_btn_icon" v-else src="https://image1.sansancloud.com/xianhua/2019_8/2/15/21/34_281.jpg?x-oss-process=style/preview_120"></image>
        <text v-if="!showMeasureListState['showMeasureListState_'+mendianProductItem.id]">展开</text>
        <text v-else>收起</text>
      </view>
      <!-- 多规格产品 -->
      <!-- animation="{{animationData}}" -->
      <view class="measure_list" v-if="showMeasureListState['showMeasureListState_'+mendianProductItem.id]">
        <view class="measure_item">
          <view class="measure_item_name">产品名</view>
          <view class="measure_item_price" style>商家供货价</view>
          <view style="padding:6rpx 16rpx;">操作</view>
        </view>
        <view class="measure_item" v-for="(measureItem, index2) in mendianProductItem.cartesians" :key="index2">
          <view class="measure_item_name">{{measureItem.measuresShow}}</view>
          <view class="measure_item_price">￥{{measureItem.storage.supplyPrice}}</view>
          <view class="measure_item_edit" :data-info="measureItem" data-type="up" @click.stop="editProductData">编辑</view>
        </view>
      </view>
    </view>
  </view>
  <view class="noList" v-else>
    <text>暂无产品~</text>
  </view>
</view>
<!-- 设置库存和价格 -->
<view class="zhezhao" v-if="showMask" @tap="closeZhezhao"></view>
<view class="add_measures_popup" v-if="showMask">
  <view class="add_measures_popup_title">
    <text>设置产品</text>
  </view>
  <form @submit="sureMeasuresData" report-submit class="add_measures_popup_list">
    <view class="add_measures_popup_item">
      <text class="add_measures_popup_item_name">供应价格</text>
      <input v-if="currentIndex!=0" type="digit" name="supplyPrice" class="add_measures_popup_item_input" :value="(selectProductItem.storage?selectProductItem.storage.supplyPrice:selectProductItem.mendianStorages[0].supplyPrice)" placeholder="请输入供应价格"></input>
      <input v-else type="digit" name="supplyPrice" class="add_measures_popup_item_input" :value="selectProductItem.supplyPrice" placeholder="请输入供应价格"></input>
    </view>
    <view class="add_measures_popup_item">
      <text class="add_measures_popup_item_name">规格状态</text>
      <picker class="picker" :data-index="stateIndex" @change="bindPickerChange" name="stock" :value="stateIndex" :range="range">
          <view class="pickerValue"><text>{{range[stateIndex]}}</text></view>
          <view class="pickerRight">
            <image class="pickerImg" src="https://image1.sansancloud.com/jianzhan/2018_9/11/13/41/53_722.jpg?x-oss-process=style/preview_120"></image>
          </view>
        </picker>
      <!-- <input type="number" name="stock" class='add_measures_popup_item_input' value='{{selectProductItem.storage.stock}}' placeholder='请输入库存'></input> -->
    </view>
    <view class="saveData">
      <button class="saveBtn" formType="submit" :style="'background:' + setting.platformSetting.defaultColor + ';color:#fff'">确定</button>
    </view>
  </form>
</view>
<!-- 扫一扫 -->
<view class="scan_popup" @click.stop="getVerificationCode">
  <view class="scan_popup_block" :style="'background:' + setting.platformSetting.defaultColor">
    <image class="scan_popup_icon" src="https://image1.sansancloud.com/xianhua/2019_8/27/17/10/46_737.jpg?x-oss-process=style/preview_120"></image>
  </view>
  <text style="margin-top:10rpx;">扫一扫</text>
</view>
</view>
</template>

<script>

export default {
  data() {
    return {
      mendianProductsList: null,
      tabItem: [{
        text: "出售中",
        status: 1,
        params: {
          status: 1
        }
      }, {
        text: "已售罄",
        status: 2,
        params: {
          status: 2
        }
      }, {
        text: "商品库",
        status: 0,
        params: {
          status: 0
        }
      }],
      currentIndex: 1,
      showHandleListState: {},
      showMeasureListState: {},
      animationData: {},
      //抽屉
      showMask: false,
      selectProductItem: null,
      range: ['缺货', '有货'],
      stateIndex: 1,
      searchProductName: '',
      productType: null,
      productTypePopupState: false,
      params: {},
      listPage: {
        page: 1,
        pageSize: 0,
        totalSize: 0
      },
      setting: "",
      loginUser: ""
    };
  },
  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('===options===', options);
    let that = this;
    that.findMendianProductsList();
    that.getProductType();
    console.log("===loginUser====", that.loginUser);
    console.log("===setting====", that.setting);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let that = this;
    that.setData({
      setting: getApp().globalData.setting,
      loginUser: getApp().globalData.loginUser
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.listPage.page = 1;
    this.findMendianProductsList();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log('===onReachBottom====');
    var that = this;

    if (that.listPage.totalSize > that.listPage.page * that.listPage.pageSize) {
      that.listPage.page++;
      this.findMendianProductsList();
    } else {
      wx.showToast({
        title: '到底啦~',
        image: '/wxcomponents/images/icons/tip.png',
        //image的优先级会高于icon
        duration: 1000
      });
    }
  },
  methods: {
    selectPopupType: function () {
      let that = this;
      that.setData({
        productTypePopupState: true
      });
    },

    getChilrenPopupType(e) {
      console.log("======getChilrenPopupType=========", e);
      let that = this;

      if (e.detail.id || e.detail.id == 0) {
        that.params.categoryId = e.detail.id;
      }

      that.setData({
        productTypePopupState: false
      });

      if (that.params.categoryId || that.params.categoryId == 0) {
        that.findMendianProductsList();
      }
    },

    //获取产品分类
    getProductType: function (e, typeText) {
      console.log("====e=====", e);
      var that = this;
      var customIndex = getApp().globalData.AddClientUrl("/wx_get_categories_only_by_parent.html"); // wx.showLoading({
      //   title: 'loading'
      // })

      getApp().globalData.showToastLoading('loading', true);
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          wx.hideLoading();
          console.log("==res====", res.data);

          if (res.data.errcode == 0) {
            let productType = res.data.relateObj;
            that.setData({
              productType: productType
            });
            console.log("productType", that.productType);
          } else {}

          wx.hideLoading();
        },
        fail: function (res) {
          console.log("fail");
          wx.hideLoading();
          getApp().globalData.loadFail();
        }
      });
    },

    /* 查找商品 */
    getSearchProductName: function (e) {
      var that = this;
      console.log("getSearchProductName", e.detail.value);

      if (e.detail.value) {
        that.params.name = e.detail.value;
      } else {
        that.params.name = '';
        that.setData({
          searchProductName: that.params.name
        });
      }

      that.findMendianProductsList();
    },
    bindPickerChange: function (event) {
      console.log('====index=====', event);
      let that = this;
      let value = event.detail.value;
      that.setData({
        stateIndex: Number(value)
      });
      console.log("===stateIndex====", that.stateIndex);
    },
    soldOutFun: function (e) {
      let that = this;
      console.log("=======soldOutFun========", e);
      let productInfo = e.currentTarget.dataset.info;
      that.setData({
        selectProductItem: productInfo
      });
      let productId = productInfo.id;
      let params = {
        productId: productId,
        stock: -1,
        cartesianId: 0
      };
      wx.showModal({
        title: '提示',
        content: '您确定要下架该产品嘛！',
        success: function (res) {
          if (res.confirm) {
            that.setMendianProductStorage(params);
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      });
    },
    putAwayFun: function (e) {
      let that = this;
      console.log("=======putAwayFun========", e);
      let productInfo = e.currentTarget.dataset.info;
      that.setData({
        selectProductItem: productInfo
      });
      wx.showModal({
        title: '提示',
        content: '您确定要上架该产品嘛！',
        success: function (res) {
          if (res.confirm) {
            that.setData({
              showMask: true,
              stateIndex: 1
            }); // that.setMendianProductStorage(params)
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      });
    },
    editProductData: function (e) {
      let that = this;
      console.log("=======editProductData========", e);
      let productInfo = e.currentTarget.dataset.info;
      let type = e.currentTarget.dataset.type;
      let productId = productInfo.itemId;
      let cartesianId = productInfo.id;
      that.setData({
        selectProductItem: productInfo
      });
      that.setData({
        showMask: true,
        stateIndex: productInfo.storage ? Number(productInfo.storage.stock) : productInfo.mendianStorages[0].stock
      }); // if (type=='down'){
      //   let params = { productId: productId, stock: -1, cartesianId: cartesianId }
      //   wx.showModal({
      //     title: '提示',
      //     content: '您确定要下架该产品嘛！',
      //     success: function (res) {
      //       if (res.confirm) {
      //         that.setMendianProductStorage(params)
      //       } else if (res.cancel) {
      //         console.log('用户点击取消')
      //       }
      //     }
      //   })
      // }else{
      //   that.setData({ showMask: true, stateIndex: productInfo.storage ? Number(productInfo.storage.stock) : 1})
      // }
    },
    tolinkUrl: function (e) {
      console.log(e.currentTarget.dataset.info); // product_detail.html?productId= 9219;

      let productData = e.currentTarget.dataset.info;
      let link = "";

      if (productData.productType == 6) {
        link = "ticket_detail.html?productId=" + productData.id;
      } else {
        link = "product_detail.html?productId=" + productData.id;
      } // var a = "product_detail.html?productId=" + e.currentTarget.dataset.id; 


      getApp().globalData.linkEvent(link);
    },
    closeZhezhao: function () {
      let that = this;
      let showHandleListState = that.showHandleListState;

      for (let i in showHandleListState) {
        showHandleListState[i] = false;
      }

      this.setData({
        showMask: false,
        showHandleListState: showHandleListState
      });
      let animation = wx.createAnimation({
        duration: 400,
        timingFunction: 'ease'
      });
      animation.bottom('-100rpx').step();
      let setData = animation.export();
      this.setData({
        animationData: setData
      });
    },
    sureMeasuresData: function (e) {
      console.log("======sureMeasuresData=======", e);
      let that = this;
      let selectProductItem = that.selectProductItem;
      let resultData = e.detail.value;

      if (!selectProductItem.measuresShow) {
        resultData = Object.assign({}, resultData, {
          productId: selectProductItem.id
        });
      } else {
        resultData = Object.assign({}, resultData, {
          productId: selectProductItem.itemId,
          cartesianId: selectProductItem.id
        });
      }

      that.setMendianProductStorage(resultData);
      that.closeZhezhao();
    },
    setMendianProductStorage: function (data) {
      let that = this;
      let selectProductItem = that.selectProductItem;
      getApp().globalData.showToastLoading('loading', true);
      let customIndex = getApp().globalData.AddClientUrl("/wx_set_mendian_product_storage.html", data);
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log('====setMendianProductStorage-res===', res);
          let successData = res.data.relateObj;

          if (res.data.errcode == 0) {
            wx.showToast({
              title: '操作成功~',
              icon: 'success',
              duration: 1000
            });
            let mendianProductsList = that.mendianProductsList;

            for (let i = 0; i < mendianProductsList.length; i++) {
              if (!selectProductItem.measuresShow) {
                console.log("=====主产品======", selectProductItem);

                if (mendianProductsList[i].id == selectProductItem.id) {
                  mendianProductsList.splice(i, 1);
                }
              } else {
                console.log("=====产品规格======", selectProductItem);

                if (mendianProductsList[i].id == successData.itemId) {
                  console.log("=======1======", mendianProductsList[i]);

                  for (let j = 0; j < mendianProductsList[i].cartesians.length; j++) {
                    if (mendianProductsList[i].cartesians[j].id == successData.id) {
                      console.log("=======2======", mendianProductsList[i].cartesians[j]);
                      mendianProductsList[i].cartesians.splice(j, 1, successData);
                    }
                  }
                }
              }
            }

            that.setData({
              mendianProductsList: mendianProductsList
            });
            that.closeZhezhao();
          } else {
            wx.showModal({
              title: '提示',
              content: res.data.errMsg + '~',
              success: function (res) {
                if (res.confirm) {// that.setMendianProductStorage(params)
                } else if (res.cancel) {
                  console.log('用户点击取消');
                }
              }
            }); // wx.showToast({
            //   title: res.data.errMsg+'~',
            //   image: '/wxcomponents/images/icons/tip.png',
            //   duration: 1000
            // })
          }
        },
        complete: function (res) {
          wx.hideLoading();
        }
      });
    },
    showMeasureListFun: function (e) {
      let that = this;
      console.log("=======showMeasureListFun========", e);
      let productId = e.currentTarget.dataset.id;
      let showMeasureListState = that.showMeasureListState;
      let state = showMeasureListState['showMeasureListState_' + productId];

      for (let i in showMeasureListState) {
        showMeasureListState[i] = false;
      }

      showMeasureListState['showMeasureListState_' + productId] = !state;
      that.setData({
        showMeasureListState: showMeasureListState
      });
      let showMeasureListState2 = showMeasureListState['showMeasureListState_' + productId];
      let animation = wx.createAnimation({
        duration: 400,
        timingFunction: 'ease'
      });
      console.log("=======popupFormPage==========", animation, this.showMeasureListState2);

      if (showMeasureListState2) {
        animation.bottom('100rpx').step();
      } else {
        animation.bottom('-100rpx').step();
      }

      this.setData({
        animationData: animation.export()
      });
    },
    showHandleListFun: function (e) {
      let that = this;
      console.log("=======showHandleListFun========", e);
      let productId = e.currentTarget.dataset.id;
      let showHandleListState = that.showHandleListState;
      let state = showHandleListState['showHandleListState_' + productId];
      console.log("=======showHandleListState1========", showHandleListState);

      for (let i in showHandleListState) {
        showHandleListState[i] = false;
      }

      showHandleListState['showHandleListState_' + productId] = !state;
      console.log("=======showHandleListState2========", showHandleListState);
      that.setData({
        showHandleListState: showHandleListState
      });
      let showHandleListState2 = !state;
      let animation = wx.createAnimation({
        duration: 400,
        timingFunction: 'ease'
      });
      console.log("=======popupFormPage==========", animation, this.showHandleListState2);

      if (showHandleListState2) {
        animation.height('70rpx').step();
      } else {
        animation.height('0rpx').step();
      }

      this.setData({
        animationData: animation.export()
      });
    },
    //扫一扫 核销
    getVerificationCode: function (e) {
      let that = this;
      console.log("getVerificationCode", e);
      wx.scanCode({
        onlyFromCamera: true,
        scanType: ['barCode'],
        success: scanRes => {
          console.log("getVerificationCode", scanRes, scanRes.result);
          that.params.name = scanRes.result;
          that.setData({
            searchProductName: scanRes.result
          });
          that.findMendianProductsList(); // wx.navigateTo({
          //   url: "/" + scanRes.path
          // })
        }
      });
    },
    changeProductState: function (e) {
      let that = this;
      console.log("===changeStateProcess===", e);
      let index = e.currentTarget.dataset.index;
      that.listPage.page = 1;
      that.currentIndex = index;
      that.setData({
        currentIndex: index
      });
      that.findMendianProductsList();
    },

    /* 获取数据 */
    findMendianProductsList: function () {
      let that = this;
      getApp().globalData.showToastLoading('loading', true);
      let params = Object.assign({}, that.params, {
        status: that.currentIndex,
        page: that.listPage.page
      });
      let customIndex = getApp().globalData.AddClientUrl("/wx_find_mendian_products.html", params);
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          console.log('====findMendianProductsList-res===', res);

          if (res.data.errcode == 0) {
            let dataArr = that.mendianProductsList;
            that.listPage.pageSize = res.data.relateObj.pageSize;
            that.listPage.totalSize = res.data.relateObj.totalSize;

            if (!res.data.relateObj.result || res.data.relateObj.result.length == 0 || that.listPage.page == 1) {
              dataArr = [];
            }

            dataArr = dataArr.concat(res.data.relateObj.result);
            let showMeasureListState = that.showMeasureListState;
            let showHandleListState = that.showHandleListState;

            for (let i = 0; i < dataArr.length; i++) {
              showMeasureListState['showMeasureListState_' + dataArr[i].id] = false;
              showHandleListState['showHandleListState_' + dataArr[i].id] = false;
            }

            that.setData({
              mendianProductsList: dataArr,
              showMeasureListState: showMeasureListState,
              showHandleListState: showHandleListState
            });
          } else {
            wx.showModal({
              title: '提示',
              content: '主人~请求超时！确认重新加载',
              success: function (res) {
                if (res.confirm) {
                  that.getUserCardPackage();
                } else if (res.cancel) {
                  console.log('用户点击取消');
                }
              }
            });
          }
        },
        complete: function (res) {
          wx.hideLoading();
        }
      });
    },
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>
@import "./index.css";
</style>